﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VOL.Core.Utilities;
using VOL.Domain.Infrastructure;
using VOL.Domain.IServices.MasterData;
using VOL.Entity.DomainModels;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace VOL.Domain.Services.MasterData
{
    public class WorkshopSettingService : IWorkshopSettingService
    {
        private readonly IBaseRepository<WorkshopSetting> _repository;

        public WorkshopSettingService(IBaseRepository<WorkshopSetting> repository)
        {
            _repository = repository;
        }

        public async Task<WebResponseContent> AddWorkshopSetting(WorkshopSetting workshopSetting)
        {
            var response = new WebResponseContent();
            
            // 检查车间编码是否已存在
            if (await _repository.GetAll(x => x.WorkshopCode == workshopSetting.WorkshopCode).AnyAsync())
            {
                return response.Error("车间编码已存在");
            }

            try
            {
                await _repository.Add(workshopSetting);
                return response.OK("添加成功");
            }
            catch (Exception ex)
            {
                return response.Error("添加失败：" + ex.Message);
            }
        }

        public async Task<WebResponseContent> GetWorkshopSettings(string workshopCode, string workshopName, int pageIndex, int pageSize)
        {
            var response = new WebResponseContent();
            
            try
            {
                var query = _repository.GetAll();

                // 应用查询条件
                if (!string.IsNullOrEmpty(workshopCode))
                {
                    query = query.Where(x => x.WorkshopCode.Contains(workshopCode));
                }
                if (!string.IsNullOrEmpty(workshopName))
                {
                    query = query.Where(x => x.WorkshopName.Contains(workshopName));
                }

                // 计算总记录数
                var total = await query.CountAsync();

                // 获取分页数据
                var list = await query
                    .OrderByDescending(x => x.Id)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                return response.OK(null, new { total, list });
            }
            catch (Exception ex)
            {
                return response.Error("获取数据失败：" + ex.Message);
            }
        }

        public async Task<WebResponseContent> UpdateWorkshopSetting(WorkshopSetting workshopSetting)
        {
            var response = new WebResponseContent();
            
            var existingSetting = await _repository.GetAll(x => x.Id == workshopSetting.Id).FirstOrDefaultAsync();
            if (existingSetting == null)
            {
                return response.Error("车间设置不存在");
            }

            // 检查车间编码是否与其他记录重复
            if (await _repository.GetAll(x => x.WorkshopCode == workshopSetting.WorkshopCode && x.Id != workshopSetting.Id).AnyAsync())
            {
                return response.Error("车间编码已存在");
            }

            try
            {
                // 更新实体属性
                existingSetting.WorkshopCode = workshopSetting.WorkshopCode;
                existingSetting.WorkshopName = workshopSetting.WorkshopName;
                existingSetting.Status = workshopSetting.Status;
                existingSetting.Area = workshopSetting.Area;
                existingSetting.Principal = workshopSetting.Principal;
                existingSetting.Descs = workshopSetting.Descs;
                existingSetting.Img = workshopSetting.Img;

                await _repository.Update(existingSetting);
                return response.OK("更新成功");
            }
            catch (Exception ex)
            {
                return response.Error("更新失败：" + ex.Message);
            }
        }

        public async Task<WebResponseContent> BatchDeleteWorkshopSettings(int[] ids)
        {
            var response = new WebResponseContent();

            if (ids == null || ids.Length == 0)
            {
                return response.Error("请选择要删除的记录");
            }

            try
            {
                var settings = await _repository.GetAll(x => ids.Contains(x.Id)).ToListAsync();
                if (!settings.Any())
                {
                    return response.Error("未找到要删除的记录");
                }

                foreach (var setting in settings)
                {
                    await _repository.Delete(setting);
                }

                return response.OK($"成功删除{settings.Count}条记录");
            }
            catch (Exception ex)
            {
                return response.Error("删除失败：" + ex.Message);
            }
        }
    }
}
